<template>
  <div class="app-container">
    <el-form label-position="top" ref="ruleForm" label-width="100px" class="demo-ruleForm">
      <el-form-item>
        <div class="title">{{ plan.name }}</div>
      </el-form-item>
      <el-form-item label="背景分析" required>
        <div class="flex" v-for="(item, ind) in backgroundPlanItemList" :key="ind">
          <el-card style="flex: 1">
            <MultiInput :type="planType" :text.sync="item.content" :province.sync="item.province" title="背景分析"/>
          </el-card>
          <div class="btn-box" v-if="planType !== 1">
            <el-button type="primary" icon="el-icon-plus" plain circle @click="addBg"></el-button>
            <el-button type="danger" v-if="ind >= 1" plain icon="el-icon-minus" circle
                       @click="removeBg(item, ind)"></el-button>
          </div>
        </div>
      </el-form-item>
      <el-form-item label="市场分析" required>
        <div class="flex" v-for="(item, ind) in marketPlanItemList" :key="ind">
          <el-card style="flex: 1">
            <MultiInput :type="planType" title="市场分析" :province.sync="item.province" :text.sync="item.content"/>
            <MultiLineTable :type="planType" :tableData="item.children"/>
          </el-card>
          <div class="btn-box" v-if="planType !== 1">
            <el-button type="primary" icon="el-icon-plus" plain circle @click="addMarket"></el-button>
            <el-button type="danger" v-if="ind >= 1" icon="el-icon-minus" plain circle
                       @click="removeMarket(item, ind)"></el-button>
          </div>
        </div>
      </el-form-item>
      <el-form-item label="客户分析" required>
        <div class="flex">
          <el-card style="flex: 1">
            <span style="font-weight: bolder">重点客户（已合作或有明确采购计划）</span>
            <MultiAgentTable :type="planType" :tableData="keyData" :listType="0"/>
            <span style="font-weight: bolder">普通客户（有潜在需求但需推进合作）</span>
            <MultiAgentTable :type="planType" :tableData="ordinaryData" :listType="1"/>
            <span style="font-weight: bolder">潜在客户（需长期培育或政策驱动）</span>
            <MultiAgentTable :type="planType" :tableData="potentialData" :listType="2"/>
          </el-card>
          <div class="btn-box" v-if="planType !== 1"></div>
        </div>
      </el-form-item>
      <el-form-item label="执行策略" required>
        <div class="flex" v-for="(item, ind) in tacticsPlanItemList" :key="ind">
          <el-card style="flex: 1">
            <MultiInput :type="planType" :text.sync="item.content" :province.sync="item.province" title="执行策略"/>
          </el-card>
          <div class="btn-box" v-if="planType !== 1">
            <el-button type="primary" icon="el-icon-plus" plain circle @click="addTa"></el-button>
            <el-button type="danger" v-if="ind >= 1" icon="el-icon-minus" plain circle
                       @click="removeTa(item, ind)"></el-button>
          </div>
        </div>
      </el-form-item>
      <el-form-item label="品牌打造" required>
        <div class="flex" v-for="(item, ind) in BrandPlanItemList" :key="ind">
          <el-card style="flex: 1">
            <MultiInput :type="planType" :text.sync="item.content" :province.sync="item.province" title="品牌打造"/>
          </el-card>
          <div class="btn-box" v-if="planType !== 1">
            <el-button type="primary" icon="el-icon-plus" plain circle @click="addBrand"></el-button>
            <el-button type="danger" v-if="ind >= 1" icon="el-icon-minus" plain circle
                       @click="removeBrand(item, ind)"></el-button>
          </div>
        </div>
      </el-form-item>
      <el-form-item label="团队建设">
        <div class="flex">
          <el-card style="flex: 1">
            <el-input
              :readonly="planType === 1"
              type="textarea"
              placeholder="请输入团队建设"
              show-word-limit
              v-model.trim="plan.team"
              :autosize="{ minRows: 4 }"
              @keyup.enter.native="enterHandler"
            />
          </el-card>
          <div class="btn-box" v-if="planType !== 1"></div>
        </div>
      </el-form-item>
      <el-form-item label="其他事宜">
        <div class="flex">
          <el-card style="flex: 1">
            <el-input
              :readonly="planType === 1"
              type="textarea"
              placeholder="请输入其他事宜"
              show-word-limit
              v-model.trim="plan.other"
              :autosize="{ minRows: 4 }"
              @keyup.enter.native="enterOtherHandler"
            />
          </el-card>
          <div class="btn-box" v-if="planType !== 1"></div>
        </div>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" v-if="planType !== 1" @click.native="submitForm()">确定</el-button>
        <el-button @click="goBackHandler">返回</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import {addDataApi, deleteDataApi, getDataListApi, updateDataApi} from "@/api/crm/sa/plan/detail";
import MultiInput from "@/views/crm/sa/plan/components/MultiInput.vue";
import MultiLineTable from "@/views/crm/sa/plan/components/MultiLineTable.vue";
import MultiAgentTable from "@/views/crm/sa/plan/components/MultiAgentTable.vue";

export default {
  name: "PlanDetail",
  components: {MultiLineTable, MultiInput, MultiAgentTable},
  data() {
    // type 1:背景分析2:市场分析3:客户分析4:执行策略 5:品牌打造
    return {
      // 增加和修改的数据
      plan: {
        createBy: "", // 创建人
        createTime: "", // 创建时间
        deptId: this.$store.state.user.deptId, // 部门id
        id: null, // id
        name: null, // 计划名称
        other: "", // 其他事宜
        remark: "", // 备注
        team: "", // 团队建设
        updateBy: "", // 更新人
        updateTime: "", // 更新时间
        userId: this.$store.state.user.id, // 用户id
      },
      // 查询出的数据
      BrandPlanItemList: [
        {
          content: "",
          createBy: this.$store.state.user.nickName,
          createTime: null,
          deptId: null,
          flag: 1,
          id: null,
          planId: null,
          province: "",
          remark: null,
          type: 5,
          updateBy: this.$store.state.user.nickName,
          updateTime: null,
          userId: this.$store.state.user.id,
        }
      ],
      // 背景分析
      backgroundPlanItemList: [
        {
          id: null,
          userId: this.$store.state.user.id,
          planId: null,
          province: "",
          content: "",
          type: 1,
          flag: 1,
          remark: null,
          createTime: "",
          createBy: this.$store.state.user.nickName,
          updateTime: null,
          updateBy: this.$store.state.user.nickName,
          deptId: null,
        }
      ],
      // 客户分析
      clientAnalysisList: [
        {
          id: null,
          userId: this.$store.state.user.id,
          planId: null,
          schoolName: "",
          basis: "",
          type: 0,
          flag: 1,
          remark: null,
          createTime: "",
          createBy: this.$store.state.user.nickName,
          updateTime: null,
          updateBy: this.$store.state.user.nickName,
          deptId: null,
        },
        {
          id: null,
          userId: this.$store.state.user.id,
          planId: null,
          schoolName: "",
          basis: "",
          type: 1,
          flag: 1,
          remark: null,
          createTime: "",
          createBy: this.$store.state.user.nickName,
          updateTime: null,
          updateBy: this.$store.state.user.nickName,
          deptId: null,
        },
        {
          id: null,
          userId: this.$store.state.user.id,
          planId: null,
          schoolName: "",
          basis: "",
          type: 2,
          flag: 1,
          remark: null,
          createTime: "",
          createBy: this.$store.state.user.nickName,
          updateTime: null,
          updateBy: this.$store.state.user.nickName,
          deptId: null,
        }
      ],
      // 品牌打造
      tacticsPlanItemList: [
        {
          id: null,
          userId: this.$store.state.user.id,
          planId: null,
          province: "",
          content: "",
          type: 4,
          flag: 3,
          remark: null,
          createTime: "",
          createBy: this.$store.state.user.nickName,
          updateTime: null,
          updateBy: this.$store.state.user.nickName,
          deptId: null,
        }
      ],
      // 市场分析
      marketPlanItemList: [
        {
          id: null,
          userId: this.$store.state.user.id,
          planId: null,
          province: "",
          content: "",
          type: 2,
          flag: 1,
          remark: null,
          createTime: "",
          createBy: this.$store.state.user.nickName,
          updateTime: null,
          updateBy: this.$store.state.user.nickName,
          deptId: null,
          children: [
            {
              amount: null,
              baseName: "",
              contactPerson: "",
              createBy: this.$store.state.user.nickName,
              createTime: "",
              decisionPerson: "",
              deptId: null,
              direction: "",
              flag: 1,
              id: null,
              planId: null,
              remark: "",
              schoolName: "",
              updateBy: this.$store.state.user.nickName,
              updateTime: null,
              userId: this.$store.state.user.id,
            }
          ],
        }
      ],
      // 重点客户
      keyData: [
        {
          id: null,
          userId: this.$store.state.user.id,
          planId: null,
          schoolName: "",
          basis: "",
          type: 0,
          flag: 1,
          remark: null,
          createTime: "",
          createBy: this.$store.state.user.nickName,
          updateTime: null,
          updateBy: this.$store.state.user.nickName,
          deptId: null,
        }
      ],
      // 普通客户
      ordinaryData: [
        {
          id: null,
          userId: this.$store.state.user.id,
          planId: null,
          schoolName: "",
          basis: "",
          type: 1,
          flag: 1,
          remark: null,
          createTime: "",
          createBy: this.$store.state.user.nickName,
          updateTime: null,
          updateBy: this.$store.state.user.nickName,
          deptId: null,
        }
      ],
      // 潜在客户
      potentialData: [
        {
          id: null,
          userId: this.$store.state.user.id,
          planId: null,
          schoolName: "",
          basis: "",
          type: 2,
          flag: 1,
          remark: null,
          createTime: "",
          createBy: this.$store.state.user.nickName,
          updateTime: null,
          updateBy: this.$store.state.user.nickName,
          deptId: null,
        }
      ],
      // 计划ID
      planId: null,
      // 操作类型
      planType: null,
    }
  },
  created() {
    // 1是查看 2是修改
    this.planId = this.$route.query.plan ?? null
    this.planType = +this.$route.query.type ?? null
    this.plan.name = this.$route.query?.name || `${new Date().getFullYear()}年销售计划`
    if (this.planId) {
      // 获取计划详情
      this.getPlanData(this.planId)
    }
  },
  activated() {
    // 1是查看 2是修改
    this.planId = this.$route.query?.plan ?? null
    this.planType = this.$route.query?.type ?? null
    this.plan.name = this.$route.query?.name ?? `${new Date().getFullYear()}年销售计划`
    if (this.planId) {
      // 获取计划详情
      this.getPlanData(this.planId)
    } else {
      Object.assign(this.$data, {
        plan: {
          createBy: "", // 创建人
          createTime: "", // 创建时间
          deptId: this.$store.state.user.deptId, // 部门id
          id: null, // id
          name: this.$route.query?.name ?? `${new Date().getFullYear()}年销售计划`, // 计划名称
          other: "", // 其他事宜
          remark: "", // 备注
          team: "", // 团队建设
          updateBy: "", // 更新人
          updateTime: "", // 更新时间
          userId: this.$store.state.user.id, // 用户id
        },
        // 查询出的数据
        BrandPlanItemList: [
          {
            content: "",
            createBy: this.$store.state.user.nickName,
            createTime: null,
            deptId: null,
            flag: 1,
            id: null,
            planId: null,
            province: "",
            remark: null,
            type: 5,
            updateBy: this.$store.state.user.nickName,
            updateTime: null,
            userId: this.$store.state.user.id,
          }
        ],
        // 背景分析
        backgroundPlanItemList: [
          {
            id: null,
            userId: this.$store.state.user.id,
            planId: null,
            province: "",
            content: "",
            type: 1,
            flag: 1,
            remark: null,
            createTime: "",
            createBy: this.$store.state.user.nickName,
            updateTime: null,
            updateBy: this.$store.state.user.nickName,
            deptId: null,
          }
        ],
        // 客户分析
        clientAnalysisList: [
          {
            id: null,
            userId: this.$store.state.user.id,
            planId: null,
            schoolName: "",
            basis: "",
            type: 0,
            flag: 1,
            remark: null,
            createTime: "",
            createBy: this.$store.state.user.nickName,
            updateTime: null,
            updateBy: this.$store.state.user.nickName,
            deptId: null,
          },
          {
            id: null,
            userId: this.$store.state.user.id,
            planId: null,
            schoolName: "",
            basis: "",
            type: 1,
            flag: 1,
            remark: null,
            createTime: "",
            createBy: this.$store.state.user.nickName,
            updateTime: null,
            updateBy: this.$store.state.user.nickName,
            deptId: null,
          },
          {
            id: null,
            userId: this.$store.state.user.id,
            planId: null,
            schoolName: "",
            basis: "",
            type: 2,
            flag: 1,
            remark: null,
            createTime: "",
            createBy: this.$store.state.user.nickName,
            updateTime: null,
            updateBy: this.$store.state.user.nickName,
            deptId: null,
          }
        ],
        // 品牌打造
        tacticsPlanItemList: [
          {
            id: null,
            userId: this.$store.state.user.id,
            planId: null,
            province: "",
            content: "",
            type: 4,
            flag: 3,
            remark: null,
            createTime: "",
            createBy: this.$store.state.user.nickName,
            updateTime: null,
            updateBy: this.$store.state.user.nickName,
            deptId: null,
          }
        ],
        // 市场分析
        marketPlanItemList: [
          {
            id: null,
            userId: this.$store.state.user.id,
            planId: null,
            province: "",
            content: "",
            type: 2,
            flag: 1,
            remark: null,
            createTime: "",
            createBy: this.$store.state.user.nickName,
            updateTime: null,
            updateBy: this.$store.state.user.nickName,
            deptId: null,
            children: [
              {
                amount: null,
                baseName: "",
                contactPerson: "",
                createBy: this.$store.state.user.nickName,
                createTime: "",
                decisionPerson: "",
                deptId: null,
                direction: "",
                flag: 1,
                id: null,
                planId: null,
                remark: "",
                schoolName: "",
                updateBy: this.$store.state.user.nickName,
                updateTime: null,
                userId: this.$store.state.user.id,
              }
            ],
          }
        ],

        // 重点客户
        keyData: [
          {
            id: null,
            userId: this.$store.state.user.id,
            planId: null,
            schoolName: "",
            basis: "",
            type: 0,
            flag: 1,
            remark: null,
            createTime: "",
            createBy: this.$store.state.user.nickName,
            updateTime: null,
            updateBy: this.$store.state.user.nickName,
            deptId: null,
          }
        ],
        // 普通客户
        ordinaryData: [
          {
            id: null,
            userId: this.$store.state.user.id,
            planId: null,
            schoolName: "",
            basis: "",
            type: 1,
            flag: 1,
            remark: null,
            createTime: "",
            createBy: this.$store.state.user.nickName,
            updateTime: null,
            updateBy: this.$store.state.user.nickName,
            deptId: null,
          }
        ],
        // 潜在客户
        potentialData: [
          {
            id: null,
            userId: this.$store.state.user.id,
            planId: null,
            schoolName: "",
            basis: "",
            type: 2,
            flag: 1,
            remark: null,
            createTime: "",
            createBy: this.$store.state.user.nickName,
            updateTime: null,
            updateBy: this.$store.state.user.nickName,
            deptId: null,
          }
        ],
        // 计划ID
        planId: null,
        // 操作类型
        planType: null,
      })
    }
  },
  methods: {
    // 执行策略
    addTa() {
      let flag = 0
      this.tacticsPlanItemList.map((item) => {
        if(item.flag > flag) flag = item.flag
      })

      this.tacticsPlanItemList.push({
        id: null,
        userId: this.$store.state.user.id,
        planId: null,
        province: "",
        content: "",
        type: 4,
        flag: flag + 1,
        remark: null,
        createTime: "",
        createBy: this.$store.state.user.nickName,
        updateTime: null,
        updateBy: this.$store.state.user.nickName,
        deptId: null,
      })
    },
    async removeTa(row, index) {
      const res = await deleteDataApi([{
        id: row.id,
        type: 1
      }])
      if(res.code === 200) {
        this.$message({
          message: res.msg,
          type: 'success'
        });
        this.tacticsPlanItemList.splice(index, 1)
      } else {
        this.$message({
          message: res.msg,
          type: 'error'
        });
      }
    },
    // 品牌打造
    addBrand() {
      let flag = 0
      this.BrandPlanItemList.map((item) => {
        if(item.flag > flag) flag = item.flag
      })
      // 增加一条品牌数据
      this.BrandPlanItemList.push({
        content: "",
        createBy: this.$store.state.user.nickName,
        createTime: null,
        deptId: null,
        flag: flag + 1,
        id: null,
        planId: null,
        province: "",
        remark: null,
        type: 5,
        updateBy: this.$store.state.user.nickName,
        updateTime: null,
        userId: this.$store.state.user.id,
      })
    },
    async removeBrand(row, index) {
      const res = await deleteDataApi([{
        id: row.id,
        type: 1
      }])
      if(res.code === 200) {
        this.$message({
          message: res.msg,
          type: 'success'
        });
        this.BrandPlanItemList.splice(index, 1);
      } else {
        this.$message({
          message: res.msg,
          type: 'error'
        });
      }
    },
    // 获取计划详情数据
    async getPlanData(id) {
      const res = await getDataListApi({id})
      if (res.code === 200) {
        this.BrandPlanItemList = res.data.BrandPlanItemList
        this.backgroundPlanItemList = res.data.backgroundPlanItemList
        this.tacticsPlanItemList = res.data.tacticsPlanItemList
        this.marketPlanItemList = res.data.marketPlanItemList
        // this.plan.team = res.data?.plan?.plan ?? ''
        // this.plan.other = res.data?.plan?.other ?? ''
        this.plan = res.data?.plan ?? {}

        this.formatMarketPlanItemList(res.data.marketAnalysisList)
        this.formatClientList(res.data.clientAnalysisList)
      }
    },
    // 整理市场分析列表
    formatMarketPlanItemList(analysisList) {
      const classified = analysisList.reduce((acc, item) => {
        if (!acc[item.flag]) {
          acc[item.flag] = [];
        }
        acc[item.flag].push(item);
        return acc;
      }, {});
      this.marketPlanItemList.map((item) => {
        item.children = classified[item.flag] ?? []
      })
    },
    // 整理客户分析列表
    formatClientList(list) {
      const classified = list.reduce((acc, item) => {
        if (!acc[item.type]) {
          acc[item.type] = [];
        }
        acc[item.type].push(item);
        return acc;
      }, {});

      if(classified['0']?.length > 0) {
        this.keyData.length = 0
      }
      if(classified['1']?.length > 0) {
        this.ordinaryData.length = 0
      }
      if(classified['2']?.length > 0) {
        this.potentialData.length = 0
      }

      list.map((item) => {
        switch (item.type) {
          case 0:
            this.keyData.push(item)
            break
          case 1:
            this.ordinaryData.push(item)
            break
          case 2:
            this.potentialData.push(item)
            break
        }
      })
    },
    // 点击回车的回调
    enterHandler() {
      // 阻止默认行为（例如表单提交）
      event.preventDefault();
      // 在某些情况下，如果你需要在文本中插入换行符，你也可以手动处理：
      this.plan.team += '\n'; // 这将导致每次回车都在文本末尾添加一个新行，但这不是必须的，因为设置了white-space和overflow-wrap后，浏览器会自动处理换行。
    },
    enterOtherHandler() {
      // 阻止默认行为（例如表单提交）
      event.preventDefault();
      // 在某些情况下，如果你需要在文本中插入换行符，你也可以手动处理：
      this.plan.other += '\n'; // 这将导致每次回车都在文本末尾添加一个新行，但这不是必须的，因为设置了white-space和overflow-wrap后，浏览器会自动处理换行。
    },
    // 市场分析增加
    addMarket() {
      let flag = 0
      this.marketPlanItemList.map((item) => {
        if(item.flag > flag) flag = item.flag
      })

      const planId = this.plan?.id ?? null

      this.marketPlanItemList.push({
        id: null,
        userId: this.$store.state.user.id,
        planId,
        province: "",
        content: "",
        type: 2,
        flag: flag + 1,
        remark: null,
        createTime: "",
        createBy: this.$store.state.user.nickName,
        updateTime: null,
        updateBy: this.$store.state.user.nickName,
        deptId: null,
        children: [
          {
            amount: null,
            baseName: "",
            contactPerson: "",
            createBy: this.$store.state.user.nickName,
            createTime: "",
            decisionPerson: "",
            deptId: null,
            direction: "",
            flag: flag + 1,
            id: null,
            planId,
            remark: "",
            schoolName: "",
            updateBy: this.$store.state.user.nickName,
            updateTime: null,
            userId: this.$store.state.user.id,
          }
        ],
      })
    },
    // 市场分析删除
    async removeMarket(item, index) {
      // 如果有id需要调用接口删除
      // 没有就不需要
      if(item.id) {
        const list = item.children.map((item) => {
          return {
            id: item.id, type: 2
          }
        })

        const res = await deleteDataApi([
          ...list,
          {
            id: item.id,
            type: 1
          },
        ])

        if(res.code === 200) {
          this.$message({
            message: res.msg,
            type: 'success'
          });
          this.marketPlanItemList.splice(index, 1);
        } else {
          this.$message({
            message: res.msg,
            type: 'error'
          });
        }
      } else {
        this.marketPlanItemList.splice(index, 1);
      }
    },
    // 背景分析增加
    addBg() {
      let flag = 0
      this.backgroundPlanItemList.map((item) => {
        if(item.flag > flag) flag = item.flag
      })

      this.backgroundPlanItemList.push({
        id: null,
        userId: this.$store.state.user.id,
        planId: null,
        province: "",
        content: "",
        type: 1,
        flag: flag + 1,
        remark: null,
        createTime: "",
        createBy: this.$store.state.user.nickName,
        updateTime: null,
        updateBy: this.$store.state.user.nickName,
        deptId: null,
      })
    },
    // 背景分析删除
    async removeBg(row, index) {
      const res = await deleteDataApi([{
        id: row.id,
        type: 1
      }])
      if(res.code === 200) {
        this.$message({
          message: res.msg,
          type: 'success'
        });
        this.backgroundPlanItemList.splice(index, 1);
      } else {
        this.$message({
          message: res.msg,
          type: 'error'
        });
      }
    },
    // 提交表单
    submitForm(formName) {
      // 提交表单
      if(this.planId) {
        const payload = this.formatPayload()
        this.updateDataHandler(payload)
      } else {
        // 整理参数
        const payload = this.formatPayload()
        // 发送请求
        this.addDataHandler({
          ...payload,
          createBy: this.$store.state.user.nickName,
        })
      }
    },
    // 增加销售计划
    async addDataHandler(payload) {
      const res = await addDataApi(payload)
      if(res.code === 200) {
        this.$message({
          message: res.msg,
          type: 'success'
        });
        this.goBackHandler()
      }
    },
    // 修改销售计划
    async updateDataHandler(payload) {
      const res = await updateDataApi(payload)
      if(res.code === 200) {
        this.$message({
          message: res.msg,
          type: 'success'
        });
        this.goBackHandler()
      }
    },
    // 整理参数
    formatPayload() {
      const marketPlanItemList = JSON.parse((JSON.stringify(this.marketPlanItemList)))
      // 文字列表
      const planItemList = []
      // 计划基本信息
      const plan = {
        ...this.plan,
        updateBy: this.$store.state.user.nickName
      }
      // 市场分析客户列表
      const marketAnalysisList = []
      // 客户分析客户列表
      const clientAnalysisList = []

      const list = marketPlanItemList.map((item) => {
        marketAnalysisList.push(...item.children)
        delete item.children
        return item
      })

      planItemList.push(
        ...this.backgroundPlanItemList,
        ...list,
        ...this.tacticsPlanItemList,
        ...this.BrandPlanItemList
      )

      clientAnalysisList.push(
        ...this.keyData,
        ...this.ordinaryData,
        ...this.potentialData
      )

      return {
        plan,
        planItemList,
        clientAnalysisList,
        marketAnalysisList
      }
    },
    // 重置表单
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
    // 页面返回
    goBackHandler() {
      this.$router.back()
    },
  }
}
</script>

<style scoped lang="scss">
.demo-ruleForm {
  max-width: 1200px;
}

.btn-box {
  width: 100px;
  margin-left: 10px;
}

.flex {
  display: flex;
  align-items: center;
}

.title {
  font-size: 28px;
  font-weight: bolder;
  text-align: center;
}
</style>
